import React, { Component } from 'react';
import { Affix, Button, Form, Icon, Popover, Select, DatePicker, Row, Col, InputNumber, message } from 'antd';
import Chooser from 'components/chooser';
import { messages ,deepCopy} from 'share/common';
import reimburseService from 'containers/expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service'
import * as Sources from 'containers/expense-reimbursement-control/expense-standard/reimbursement-submission/data-sources';
import Skeleton from 'components/skeleton';

const dataSources = deepCopy(Sources);
const FormItem = Form.Item;
const { Option } = Select;

class ReimbursementSubmissionCondition extends Component {

  component = {
    Select,
    section: 'section',
    Chooser,
    DatePicker,
    InputNumber
  };

  constructor(props) {
    super(props);
    this.state = {
      formItems: [
        {
          id: 'controlItem', // 表单key
          type: 'Select', // 采用何种组件
          show: true,  // 是否展示
          span: 24,   // 尺寸
          label: this.renderControlLabel(), // 表单item的名字
          params: { // 组件参数
            onChange: this.handleControlSelect,
          },
          required: true, // 是否必填
          children: dataSources.controlItems.map(item => <Option value={item.key}>{item.value}</Option>), // 表单子元素
          initialValue: 1006, // 默认值
        },
        {
          id: 'valueType',
          type: 'Select',
          show: true,
          span: 24,
          label: messages('expense-reimbursement-control.key14')/*取值方式*/,
          params: {},
          children: dataSources.valueCompareTypes.map(item => <Option value={item.key}>{item.value}</Option>),
          required: true,
        },
        {
          id: 'controlCond',
          type: 'Select',
          show: true,
          span: 24,
          label: messages('expense-reimbursement-control.key15')/*条件*/,
          params: {},
          children: dataSources.conditionDa.map(item => <Option value={item.key}>{item.value}</Option>),
          required: true,
        },
        {
          id: 'fieldValue',
          type: 'Chooser',
          show: true,
          span: 24,
          label: '',
          params: {},
          formItemLayout: { wrapperCol: { offset: 6, span: 18 } },
          required: true,
        },
        {
          id: 'mixedItem',
          type: 'Select',
          show: true,
          span: 12,
          label: '',
          params: {},
          required: true,
          formItemLayout: { wrapperCol: { offset: 12, span: 12 } },
        },
        {
          id: 'extendValue',
          type: 'Chooser',
          show: true,
          span: 12,
          label: '',
          params: {},
          required: true,
          formItemLayout: { wrapperCol: { offset: 2, span: 20 } },
        }
      ],
      standard: {},
      loading: false
    };
  }

  componentDidMount() {
    const { params: { itemOID } } = this.props;
    if (itemOID) {
      const service = () => {
        reimburseService.searchControl(itemOID)
          .then(res => {
            console.log(res.data);
            let standard = res.data;
            this.setState({ standard }, () => this.handleControlSelect(standard.controlItem, standard));
          })
          .finally(() => {
            this.setState({ loading: false });
          });
      };
      this.setState({ loading: true }, service);
    } else {
      this.handleControlSelect(dataSources.controlItems[5].key);
    }
  }

  handleControlSelect = (value, standard = {}) => {
    let { formItems } = this.state;
    const { params: { setOfBooksId },form:{setFieldsValue} } = this.props;
    this.props.form.resetFields();
    dataSources.controlItems.some(control => {
      if (control.key === value) {
        formItems.map(item => {
          if (item.id === 'mixedItem' || item.id === 'controlCond' || item.id === 'valueType') {
            item.show = !!control[item.id];
            if (item.show) {
              item.children = dataSources[control[item.id]].map(ret => <Option
                value={ret.key}>{ret.value}</Option>);
            }
            return item;
          }

          if (item.id === 'extendValue' || item.id === 'fieldValue') {
            item.show = !!control[item.id];
            if (item.show) {
              item.type = control[item.id].type;
              if (control[item.id].type === 'Chooser') {
                item.params = {
                  onChange: () => {},
                  onlyNeed:'expenseTypeOID',
                  type: 'selectInvoiceType',
                  valueKey: 'expenseTypeOID',
                  labelKey: 'name',
                  listExtraParams: {
                    enabled: true,
                    setOfBooksId
                  }
                };
              }
              if (control[item.id].type === 'InputNumber') {
                item.params = {
                  precision: 0,
                  min: 1,
                  max: 9999,
                  style: { width: '100%' }
                };
              }
            }
          }
          return item;
        });
        return true;
      }
    });
    this.setState({ formItems }, () => {setFieldsValue(standard);});
  };

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { params: { ruleOID } } = this.props;
        const { standard } = this.state;
        let serviceFlag = 'saveControl';
        if (standard.itemOID) {
          values.itemOID = standard.itemOID;
          serviceFlag = 'updateControl';
        }
        const service = () => {
          reimburseService[serviceFlag](ruleOID, values)
            .then(() => {
              this.props.close('standard');
              message.success(`${messages('common.save.success', { name: '' })}`);
            })
            .finally(() => {
              this.state({ submitLoading: false });
            });
        };
        this.setState({ submitLoading: true }, service);
      }
    });
  };

  handleCancel = () => {
    this.props.close();
  };

  renderFormItem = (item) => {
    return React.createElement(this.component[item.type], item.params, item.children);
  };

  renderControlLabel = () => {
    const desc = [
      messages('expense-reimbursement-control.key134')/*费用发生日期获取优先级：*/,
      messages('expense-reimbursement-control.key135')/*1、补贴明细日期*/,
      messages('expense-reimbursement-control.key136')/*2、开始结束日期*/,
      messages('expense-reimbursement-control.key137')/*3、费用发生日期]*/
    ];
    return (
      <Popover content={desc.map(item => <div>{item}</div>)}>
        {messages('expense-reimbursement-control.key12')/*管控项*/} <Icon type="info-circle" className='default-color-font reimbursement-submission-icon'/>
      </Popover>
    );
  };

  render() {
    const { formItems, submitLoading, loading } = this.state;
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
    const { form: { getFieldDecorator }, params: { itemOID } } = this.props;
    return (
      <section className="reimbursement-submission">
        <Form onSubmit={this.handleSave}>
          <Skeleton loading={loading}>
            <Row>
              {formItems.map(item => {
                let rules = [{ required: item.required, message: messages('common.please.enter') }];
                const layout = { ...formItemLayout, ...item.formItemLayout };
                if (item.rules) rules.push(item.rules);
                return (
                  item.show
                    ? <Col span={item.span}>
                      <FormItem label={item.label}  {...layout}>
                        {
                          getFieldDecorator(item.id,
                            {
                              rules: rules,
                              valuePropName: item.valuePropName || 'value',
                              initialValue: item.initialValue
                            }
                          )(this.renderFormItem(item))
                        }
                      </FormItem>
                    </Col>
                    : null
                );
              })}
            </Row>
          </Skeleton>
          <Affix offsetBottom={0} className="reimbursement-submission-footer reimbursement-submission-left">
            <Button type="primary" htmlType="submit" loading={submitLoading}>
              { itemOID? messages('common.save'/*保存*/) : messages('expense-reimbursement-control.key26')/*创建*/}
            </Button>
            <Button onClick={this.handleCancel} className="reimbursement-submission-cancel">
              {messages('common.cancel')/*取消*/}
            </Button>
          </Affix>
        </Form>
      </section>
    );
  }
}

ReimbursementSubmissionCondition.propTypes = {};

const WrappedComponent = Form.create()(ReimbursementSubmissionCondition);

export default WrappedComponent;
